﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Card.Make.Pro.Application.Dapper;
using DevExpress.XtraEditors;
using DevExpress.XtraRichEdit.Model;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;

namespace Card.Make.Pro.Form
{
    public partial class FrmStats : DevExpress.XtraEditors.XtraForm
    {
        public FrmStats()
        {
            InitializeComponent();
            _dapperClient = new DapperClient(new Config() { ConnectionString = Properties.Settings.Default.ConnectionString, DbType = DbStoreType.SqlServer });
        }



        /// <summary>
        /// dapper client
        /// </summary>
        private readonly DapperClient _dapperClient;


        /// <summary>
        /// 刷新设备列表
        /// </summary>
        private void RefreshDeviceList()
        {

        }


        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void FrmDeviceState_Load(object sender, EventArgs e)
        {

            dteStartTime.Properties.VistaEditTime = DevExpress.Utils.DefaultBoolean.True;
            dteStartTime.Properties.VistaTimeProperties.EditMask = "HH:mm:ss";
            dteStartTime.Properties.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
            dteStartTime.Properties.EditMask = "yyyy-MM-dd HH:mm:ss";

            dteEndTime.Properties.VistaEditTime = DevExpress.Utils.DefaultBoolean.True;
            dteEndTime.Properties.VistaTimeProperties.EditMask = "HH:mm:ss";
            dteEndTime.Properties.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
            dteEndTime.Properties.EditMask = "yyyy-MM-dd HH:mm:ss";

            dteStartTime.EditValue = "2020-01-01 00:00:00";
            dteEndTime.EditValue = DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59";

            ChangeSettingEnable();

            LoadCardType();
            LoadDevices();

            Query();
        }

        /// <summary>
        /// 加载证件类型
        /// </summary>
        private void LoadCardType()
        {
            var sql = "SELECT  DISTINCT [CardType] AS Name  FROM [Card_Table]";
            var dt = _dapperClient.ExecuteDataTable(sql);

            tvwCardTypeList.DataSource = dt;

        }


        /// <summary>
        /// 是否启用证卡类型选项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkCardTypeList_CheckedChanged(object sender, EventArgs e)
        {
            tvwCardTypeList.OptionsView.CheckBoxStyle = chkCardTypeList.Checked ? DefaultNodeCheckBoxStyle.Check : DefaultNodeCheckBoxStyle.Default;
        }

        /// <summary>
        /// 加载设备
        /// </summary>
        private void LoadDevices()
        {
            var sql = "SELECT * FROM [dbo].[Device_Table]  ORDER BY  DeviceType,DeviceID";
            var dt = _dapperClient.ExecuteDataTable(sql);
            tvwDeviceList.DataSource = dt;
            tvwDeviceList.KeyFieldName = "DeviceID";
            tvwDeviceList.ParentFieldName = "ParentID";
            tvwDeviceList.ExpandAll();
        }

        /// <summary>
        /// 控点选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkDeviceList_CheckedChanged(object sender, EventArgs e)
        {
            tvwDeviceList.OptionsView.ShowCheckBoxes = chkDeviceList.Checked;
        }


        /// <summary>
        /// 查询
        /// </summary>
        private void Query()
        {

            var strWhere = $" AND CreateDT>='{ dteStartTime.EditValue}'";
            if (chkEndTime.Checked && !string.IsNullOrWhiteSpace(dteEndTime.EditValue.ToString()))
                strWhere += $" AND CreateDT<'{dteEndTime.EditValue.ToString()}'";

            if (chkCardTypeList.Checked)
            {
                var cardTypes = new List<string>();
                foreach (TreeListNode node in tvwCardTypeList.Nodes)
                {
                    if (node.CheckState == CheckState.Checked) //判断当前节点选择状态
                    {
                        var name = node.GetValue("Name");
                        cardTypes.Add(name?.ToString());
                    }
                }

                if (cardTypes.Any())
                {
                    strWhere += " AND CardType IN (" + string.Join(",", cardTypes.Select(_ => "'" + _ + "'")) + ")";
                }
            }

            var sql = $@"SELECT CardType,COUNT(1) AS Total,
SUM(CASE WHEN IFPrinted=1 THEN 1 ELSE 0 END) AS PrintedTotal,
SUM(CASE WHEN IFPrinted=0 THEN 1 ELSE 0 END) AS UnprintedTotal
 FROM dbo.Card_Table
WHERE 1=1 {strWhere}
GROUP BY CardType";
            var dt = _dapperClient.ExecuteDataTable(sql);
            var xData = new List<string>();
            var yData = new List<int>();
            foreach (DataRow row in dt.Rows)
            {
                xData.Add(row["CardType"] + " " + row["Total"]);
                yData.Add(Convert.ToInt32(row["Total"]));
            }
            chart2.Titles.Clear();
            chart2.Titles.Add("证卡分类统计");
            chart2.Series[0]["PieLabelStyle"] = "Outside";//将文字移到外侧
            chart2.Series[0]["PieLineColor"] = "Black";//绘制黑色的连线。
            chart2.Series[0].Points.DataBindXY(xData, yData);

            chart1.Titles.Clear();
            chart1.Titles.Add("证件类型制作量统计");
            chart1.DataSource = dt;
            chart1.Series[0].YValueMembers = "Total";
            chart1.Series[1].YValueMembers = "PrintedTotal";
            chart1.Series[2].YValueMembers = "UnprintedTotal";

            chart1.Series[0].Name = "总数";
            chart1.Series[1].Name = "已打印";
            chart1.Series[2].Name = "未打印";

            chart1.Series[0].XValueMember = "CardType";
            chart1.Series[1].XValueMember = "CardType";
            chart1.Series[2].XValueMember = "CardType";

            chart1.DataBind();


            sql = $@"SELECT  CONVERT(varchar(20), PrintDT, 111) AS DT,COUNT(1) AS Total
FROM dbo.Card_Table 
WHERE PrintDT IS NOT NULL {strWhere}
GROUP BY  CONVERT(varchar(20), PrintDT, 111)";
            dt = _dapperClient.ExecuteDataTable(sql);
            chart3.Titles.Clear();
            chart3.Titles.Add("制作量统计图");
            chart3.Series[0].Name = "制作量";
            chart3.DataSource = dt;
            chart3.Series[0].XValueMember = "DT";
            chart3.Series[0].YValueMembers = "Total";
            chart3.DataBind();
        }

        private void butCardTypeStatRefresh_Click(object sender, EventArgs e)
        {
            Query();
        }


        /// <summary>
        /// 更改查询条件禁用状态
        /// </summary>
        private void ChangeSettingEnable()
        {
            var idx = tctlStats.SelectedTabPage.Name;
            if (idx == "tpCardTypeStat")
            {
                chkEventType.Enabled = false;
                cklEventType.Enabled = false;

                chkDeviceList.Enabled = false;
                tvwDeviceList.Enabled = false;
            }
            else
            {
                chkEventType.Enabled = true;
                cklEventType.Enabled = true;

                chkDeviceList.Enabled = true;
                tvwDeviceList.Enabled = true;
            }
        }

        /// <summary>
        /// 选择项更改后触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tctlStats_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            ChangeSettingEnable();
        }

        // ===================================================流水统计相关========================================
        /// <summary>
        /// 流水统计
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butHisStat_Click(object sender, EventArgs e)
        {
            QueryHis();
        }



        /// <summary>
        /// 查询
        /// </summary>
        private void QueryHis()
        {
            // 统计类型
            var statType = rdogStatType.SelectedIndex;
            if (statType == 1 && !string.IsNullOrWhiteSpace(dteStartTime.EditValue.ToString()))
            {
                dteStartTime.EditValue =
                    Convert.ToDateTime(dteStartTime.EditValue).ToString("yyyy-MM-dd") + " 00:00:00";
                dteEndTime.EditValue =
                    Convert.ToDateTime(dteStartTime.EditValue).ToString("yyyy-MM-dd") + " 23:59:59";

                chkEndTime.Checked = true;
            }

            var strWhere = $" AND EventDT>='{ dteStartTime.EditValue}'";
            if (chkEndTime.Checked && !string.IsNullOrWhiteSpace(dteEndTime.EditValue.ToString()))
                strWhere += $" AND EventDT<='{dteEndTime.EditValue.ToString()}'";


            // 事件类型
            if (chkEventType.Checked)
            {
                var eventTypes = new List<int>();
                var checkedItems = this.cklEventType.Items.Where(x => x.CheckState == CheckState.Checked);
                foreach (var checkedItem in checkedItems)
                {
                    var item = checkedItem.Value;
                    eventTypes.Add(Convert.ToInt32(item));
                }

                if (eventTypes.Any())
                {
                    strWhere += $" AND EventType IN ({string.Join(",", eventTypes)})";
                }
            }
            // 控点
            if (chkDeviceList.Checked)
            {
                var ids = new List<int>();
                foreach (TreeListNode node in tvwDeviceList.Nodes)
                {
                    GetCheckedValues(node, ids);
                }
                if (ids.Any())
                {
                    strWhere += $" AND DomainID IN ({string.Join(",", ids)})";
                }
            }
            // 证件类型
            if (chkCardTypeList.Checked)
            {
                var names = new List<string>();
                foreach (TreeListNode node in tvwCardTypeList.Nodes)
                {
                    if (!node.Checked)
                    {
                        continue;
                    }

                    var row = tvwCardTypeList.GetDataRecordByNode(node) as DataRowView;
                    var name = row["Name"];
                    names.Add($"'{name}'");
                }
                if (names.Any())
                {
                    strWhere += $" AND CardType IN ({string.Join(",", names)})";
                }
            }
            // 进出标识
            var inOutIndex = rdogInOutTag.SelectedIndex;
            inOutIndex = inOutIndex == 0 ? 1 : 2;
            strWhere += $" AND InOutTag = {inOutIndex }";


            var sql =
                $"SELECT CONVERT(varchar(20), EventDT, 111) AS DT,COUNT(*) Total FROM HisList_Table WHERE 1=1 {strWhere}  GROUP BY CONVERT(varchar(20), EventDT, 111) ORDER BY CONVERT(varchar(20), EventDT, 111)";
            // 按照小时统计
            if (statType == 1)
            {
                sql = $@"SELECT COUNT(*) Total,DATEPART(hh,EventDT) H FROM HisList_Table
WHERE 1=1 {strWhere}
GROUP BY DATEPART(hh,EventDT) ORDER BY DATEPART(hh,EventDT)";
            }

            var dt = _dapperClient.ExecuteDataTable(sql);
            if (dt.Rows.Count == 0)
            {
                XtraMessageBox.Show("统计数据不存在，请更改统计条件后继续", "统计消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            // 统计类型
            var title = statType == 0
                  ? $"按照天统计（{(inOutIndex == 1 ? "进" : "出")}）"
                  : $"按照小时统计（{(inOutIndex == 1 ? "进" : "出")}）";
            if (statType == 1)
            {
                dt.Columns.Add("DT", Type.GetType("System.String"));
            }

            foreach (DataRow row in dt.Rows)
            {
                if (statType == 0)
                    row["DT"] = Convert.ToDateTime(row["DT"]).ToString("MM-dd");
                else
                    row["DT"] = row["H"].ToString().Length == 1 ? "0" + row["H"].ToString() + ":00" : row["H"].ToString() + ":00";
            }
            chart4.Titles.Clear();
            chart4.DataSource = dt;
            chart4.Titles.Add(title);
            chart4.Series[0].Name = "流量";
            chart4.Series[0].XValueMember = "DT";
            chart4.Series[0].YValueMembers = "Total";
            chart4.DataBind();

            gridControl1.DataSource = dt;
        }

        public void GetCheckedValues(TreeListNode nodes, List<int> ids)
        {
            if (nodes.Nodes.Count == 0)
            {
                return;
            }

            foreach (TreeListNode node in nodes.Nodes)
            {
                if (node.CheckState == CheckState.Checked)
                {
                    var row = tvwDeviceList.GetDataRecordByNode(node) as DataRowView;
                    var deviceId = row["DeviceID"];
                    if (row["DeviceType"].ToString().Equals("3")) ids.Add(Convert.ToInt32(deviceId));
                }

                GetCheckedValues(node, ids);
            }
        }
    }
}
